package com.jswty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.ByteOrder;

import static io.netty.util.CharsetUtil.UTF_8;

/**
 * @author senowang
 * @date 2018/10/15 - 15:24
 */
public class ZabbixAgent {
    
    
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "10055"));
    
    public static void main(String[] args) throws Exception {
        
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.DEBUG));
                            p.addLast(new LengthFieldBasedFrameDecoder(
                                    //小端模式
                                    ByteOrder.LITTLE_ENDIAN,
                                    //消息允许最大长度
                                    104857600,
                                    //消息长度在消息体里面的偏移量
                                    5,
                                    //消息长度字段占用长度
                                    8,
                                    //长度调整 消息包的长度 和消息头里面的长度是否一致，是否要减去消息头
                                    0,
                                    //跳过不是消息部分的长度（整个消息体去掉消息头的协议和消息长度）
                                    13,
                                    true));
                            p.addLast(new StringDecoder(UTF_8));
                            p.addLast(new ZabbixAgentHandler());
                        }
                     });
            
            // Start the client.
            ChannelFuture f = b.connect(HOST, PORT).sync();
            
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }
}
